// const MYAPI = require('apimyphp')
const CONFIG = require('../siteinfo.js')
//登录注册相关----------------------------开始----------------------------------------------------------------------------------------------------------------
// 异步登录，此时不可以得到头像
async function asyncLogin(page){
    const _this = this
    const _page = page
    return new Promise((resolve, reject) => {
        //如果存在token22或者uid，说明已经登录
        const token22 = wx.getStorageSync('token22')
        if(token22){
            return resolve(true)
        }
        wx.login({
            //如果个人中心未获取头像，则请求到的uinfostr包含的头像为空
            success: function (res) {
              let referrer = wx.getStorageSync('referrer') ? wx.getStorageSync('referrer') : 0; // 推荐人
              //以下是不包含用户头像和昵称的openid注册接口，对应我爱小区
              _this.request22('/client/apitowx/wsLogin.php?g=wsResLogin',{ jscode: res.code, pid: referrer}).then(function (res) {
                if(res.code==1){
                    console.log('login ok and get wxuser info................................................')
                    _this.getLoginResData(res, _page);
                    return resolve(true)
                }
                else{
                    return resolve(false)
                }
              })
            }
        })
    })
}
//异步注册，此时可以得到头像
async function registerTT(page) {
    const _this = this
    const _page = page
    return new Promise((resolve, reject) => {
        const _openid = wx.getStorageSync('openid')
        if(_openid==undefined || _openid==""){
            console.log('register--error--------------not find openid---------------------------------',_openid);
            return resolve(false)
        }
        //以下将直接获取到微信用户头像和昵称
        wx.getUserProfile({
            desc: '展示用户信息',
            success: function (res) {
                console.log('register--ok ok ok-----------------------------------------------',res);
                let iv = res.iv;
                let encryptedData = res.encryptedData;
                let referrer = wx.getStorageSync('referrer') ? wx.getStorageSync('referrer') : 0; // 推荐人
                // 以下是包含用户头像和昵称的注册接口，对应我爱小区
                _this.request22('/client/apitowx/wsLogin.php?g=wsResLogin',{inOpenid:_openid,pid:referrer,ivStr:iv,wuinfoStr:res.rawData}).then(function(res){
                    _this.getLoginResData(res, _page);
                    return resolve(true)
                })
            },
            fail:function(ee){
                console.log('register--error-----------------------------------------------',ee);
                return resolve(false)
            }
        })
    })
}
//登录注册相关----------------------------结束----------------------------------------------------------------------------------------------------------------




function getLoginResData(res, _page){
    if (res.code == 1) {
        var data = res.data;
        wx.setStorageSync('token22', data.wu_id)
        wx.setStorageSync('uid', data.wu_id)
        wx.setStorageSync('wu_id', data.wu_id)
        wx.setStorageSync('wu_openid', data.wu_openid)
        wx.setStorageSync('openid', data.wu_openid)
        wx.setStorageSync('access', data.u_access)
        wx.setStorageSync('u_truename', data.u_truename)
        wx.setStorageSync('wu_nickname', data.wu_nickname)
        wx.setStorageSync('wu_headimgurl', data.wu_headimgurl)
        wx.setStorageSync('u_mobile', data.u_mobile)
        
        wx.setStorageSync('uinfoStr', JSON.stringify(data))
        if (_page!=null && _page!=undefined){
        _page.setData({ wxlogin: true })
        _page.onShow()
        }
    }
}
function loginOut(){
    wx.removeStorageSync('token22')
    wx.removeStorageSync('uid')
    wx.removeStorageSync('openid')
    wx.removeStorageSync('wu_id')
    wx.removeStorageSync('wu_openid')
    wx.removeStorageSync('access')
    wx.removeStorageSync('u_truename')
    wx.removeStorageSync('wu_nickname')
    wx.removeStorageSync('wu_headimgurl')
    wx.removeStorageSync('u_mobile')
    //wx.removeStorageSync('referrer')
    wx.removeStorageSync('uinfoStr')
    wx.removeStorageSync('uMobile')
    wx.removeStorageSync('uNickName')
    wx.removeStorageSync('uHeaderImg')
}

  //其他相关----暂时未用开始-----------------------------------------------------------------------------------------------------------------------------------------------------
  // 检测登录状态，返回 true / false; 存在await的才用async修饰函数方法，暂时未用
    async function checkSession(){
        return new Promise((resolve, reject) => {
        wx.checkSession({
            success() {
            return resolve(true)
            },
            fail() {
            return resolve(false)
            }
        })
        })
    }
    // 暂时未使用
    async function checkHasLogined() {
        //return false; //一直让其处于未登录状态，做数据测试
        const token22 = wx.getStorageSync('token22')
        if (!token22) {
        return false
        }
        const loggined = await checkSession()
        if (!loggined) {
        wx.removeStorageSync('token22')
        return false
        }
        //后台判断后台的session是否过期
        return true
    }
    async function checkAndAuthorize (scope) {
        return new Promise((resolve, reject) => {
        wx.getSetting({
            success(res) {
            if (!res.authSetting[scope]) {
                wx.authorize({
                scope: scope,
                success() {
                    resolve() // 无返回参数
                },
                fail(e){
                    console.error(e)
                    // if (e.errMsg.indexof('auth deny') != -1) {
                    //   wx.showToast({
                    //     title: e.errMsg,
                    //     icon: 'none'
                    //   })
                    // }
                    wx.showModal({
                    title: '无权操作',
                    content: '需要获得您的授权',
                    showCancel: false,
                    confirmText: '立即授权',
                    confirmColor: '#e64340',
                    success(res) {
                        wx.openSetting();
                    },
                    fail(e){
                        console.error(e)
                        reject(e)
                    },
                    })
                }
                })
            } else {
                resolve() // 无返回参数
            }
            },
            fail(e){
            console.error(e)
            reject(e)
            }
        })
        })  
    }
  function test(){
    console.log('我是auth文件中的test函数.........',CONFIG.siteroot22)
  }
  //其他相关----暂时未用结束-----------------------------------------------------------------------------------------------------------------------------------------------------
  function request22(url, data) {
    var _url = CONFIG.siteroot22 + url;
    return new Promise(function (resolve, reject) {
      wx.request({
        url: _url,
        method: 'post',
        data: data,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function success(request) {
          if (request.data.code){
            return resolve(request.data);
          }
          else{
            console.log('request22----22222222222XXXXXXXXXXXX---------------------' + url + '--------------------------' + request.data);
            return resolve(request.data);
          }
        },
        fail: function fail(error) {
            return reject(error);
        },
        complete: function complete(aaa) {
          // 加载完成
        }
      });
    });
  }
  //对外暴露接口----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  module.exports = {
    checkHasLogined: checkHasLogined,
    asyncLogin:asyncLogin,
    request22:request22,
    test:test,
    registerTT:registerTT,
    loginOut: loginOut,
    getLoginResData: getLoginResData,
    checkAndAuthorize: checkAndAuthorize
  }